package cn.tedu.sk.service.impl;

import cn.tedu.sk.entity.UserInfo;
import cn.tedu.sk.entity.dto.UserLoginInfoDTO;
import cn.tedu.sk.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("loadUserByname");
        UserLoginInfoDTO userLoginInfoDTO = userMapper.selectUserByName(s);
        if (userLoginInfoDTO == null) {
            return null;
        }
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<String> permissions = userLoginInfoDTO.getPermissions();

        for (String permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission));
        }
        UserInfo userInfo = new UserInfo(
                userLoginInfoDTO.getId(),
                userLoginInfoDTO.getUsername(),
                userLoginInfoDTO.getPassword(),
                userLoginInfoDTO.getAvatar(),
                userLoginInfoDTO.getEnable() == 1,
                grantedAuthorities
        );
        return userInfo;

    }
}
